package org.pvt.gui;

import android.content.ContentValues;
import android.database.Cursor;
import android.widget.CursorAdapter;
import org.jetbrains.annotations.NotNull;
import org.pvt.model.HasName;
import org.pvt.model.HasNameAndBelongsToEvent;
import org.pvt.model.Model;
import org.pvt.model.Models;

/**
 * @author Pavel Talanov
 */
public abstract class EventAttrCRUDActivity extends BasicCRUDActivity {

    @NotNull
    protected abstract HasNameAndBelongsToEvent getModel();

    @NotNull
    @Override
    protected Cursor getNewCursor() {
        return getModel().getCursor(getEventId(), this);
    }

    @Override
    protected void addItem(@NotNull String text) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(HasName.NAME, text);
        long eventId = getEventId();
        contentValues.put(Model.referenceById(Models.Event), eventId);
        getModel().create(contentValues, this);
        resetCursorAdapter();
    }

    @Override
    protected void updateItem(long id, @NotNull String newText) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(HasName.NAME, newText);
        getModel().update(id, contentValues, this);
        resetCursorAdapter();
    }

    @Override
    protected void deleteItem(long id) {
        getModel().delete(id, this);
        resetCursorAdapter();
    }

    protected long getEventId() {
        return getIntent().getExtras().getLong(Models.Event.getExtrasName());
    }

    @Override
    @NotNull
    protected CursorAdapter getCursorAdapter(@NotNull Cursor cursor) {
        return new EventAttrCRUDCursorAdapter(this, cursor);
    }

}
